<template>
  <el-card>
    <div slot="header">
      <h3>修改品类-表单修改页面</h3>
    </div>
    <div>
      <el-row
        class="btn-action-wrap"
        type="flex"
        justify="end"
      >
        <el-button
          type="text"
          size="large"
          @click="$router.push({ name: 'chageFromManageList' })"
        >返回</el-button
        >
        <el-button
          type="text"
          size="large"
          :disabled="tableInfo.selection.length === 0"
          @click="handleCategoryLinked"
        >关联品类</el-button
        >
        <el-button
          type="text"
          size="large"
          :disabled="tableInfo.list.length === 0"
          :loading="btnLoading.submit"
          @click="handleSubmitData"
        >提交</el-button
        >
      </el-row>
    </div>
    <el-row>
      <SkusTable
        showSelectCol
        :defaultMinWidth="120"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :selectionChange="handleSelectionChange"
        @visibleChange="handleRefreshClassificationInfo"
        @selectChange="handleSelectClassification"
        @handleCancelSelect="handleRemoveRow"
      />
    </el-row>
    <FooterFields :footerFields="footerFields" />
    <!-- 关联分类弹框 -->
    <basic-dialog
      title="关联四级类"
      width="60%"
      :visible="categoryLinked.visible"
      :show-close="false"
      :showFooter="false"
    >
      <CategorySelect
        @submitConcat="handleCategoryOk"
        @cancelConcat="handleCategoryClose"
      />
    </basic-dialog>
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import BasicDialog from '@/components/BasicDialog';
import CategorySelect from './components/CategorySelect';
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import { tableColumns, showErrMsgColumns, CLASSIFICATION_OPTIONS_NAME } from './constants';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
export default {
  components: {
    BasicDialog,
    SkusTable,
    CategorySelect,
    FooterFields
  },
  data () {
    return {
      categoryLinked: {
        visible: false,
      },
      tableInfo: {
        list: [], // 表格数据
        columns: tableColumns, // 表格columns
        selection: [], // 勾选列表
        loading: false // 表格加载loading
      },
      btnLoading: {
        submit: false
      },
      footerFields: {},
      recordNo: '',
      uniqueKey: 'spuNo', // 表格数据的唯一标识key名称
      apiObj: {
        getRecordInfo: { // 单据信息查看(获取表格数据)
          url: '/sysback/modifySpuCategory/getRecordInfo',
          type: 'get'
        },
        categoryCommit: { // 单据提交
          url: '/sysback/modifySpuCategory/commit',
          type: 'post'
        },
        getBelongingDeptList: { // 归属部门查询
          url: '/sysback/srm/getBelongingDeptList',
          type: 'post'
        },
        getByCategoryUuid: { // 归类信息查询
          url: '/sysback/classification/getByCategoryUuid',
          type: 'get'
        },
        getCateInfo: { // 查询品类及归类信息
          url: '/sysback/modifySpuCategory/getCateInfo',
          type: 'get'
        }
      }
    };
  },
  mounted () {
    const { recordNo } = this.$route.query;
    this.recordNo = recordNo;
    this.getTableDataFn(recordNo);
  },
  methods: {
    // 关联品类
    handleCategoryLinked () {
      this.categoryLinked.visible = true;
    },
    // 关联品类弹框-确定
    handleCategoryOk (categoryData) {
      const { categoryUuid } = categoryData;
      this.getCateInfoByUuidFn(categoryUuid);
      this.refreshCategoryPathFn(categoryData);
      this.refreshBelongingDeptNameFn();
      this.categoryLinked.visible = false;
    },
    // 关联品类弹框-关闭
    handleCategoryClose () {
      this.categoryLinked.visible = false;
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 提交
    async handleSubmitData () {
      if (this.tableInfo.list.length === 0) {
        this.$message.warning('请关联商品');
        return false;
      }
      const data = {
        commitParamList: this.tableInfo.list,
        recordNo: this.recordNo
      };
      const { url, type } = this.apiObj.categoryCommit;
      try {
        this.btnLoading.submit = true;
        const res = await ApiRequest(url, type, data);
        this.btnLoading.submit = false;
        if (!isResponseSuccessState(res.retStatus)) {
          return false;
        }
        const { recordNo, modifiedSpuVoList } = res.retData;
        if (!recordNo) {
          const msg = '存在异常商品，无法提交';
          this.$message.warning(msg);
          this.tableInfo.columns = showErrMsgColumns;
          this.tableInfo.list = this.getProcesscedTableDataFn(modifiedSpuVoList);
          return false;
        }
        this.$message.success('提交成功');
        this.$router.push({ name: 'chageFromManageList' });
      } catch (err) {
        this.btnLoading.submit = false;
      }
    },
    // 获取表格数据
    async getTableDataFn (recordNo) {
      const data = { recordNo };
      const { url, type } = this.apiObj.getRecordInfo;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          this.tableInfo.list = this.getProcesscedTableDataFn(res.retData.modifiedSpuVoList);
          this.footerFields = res.retData;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 获取处理后的表格数据-生成归类options
    getProcesscedTableDataFn (spuVoList) {
      if (!spuVoList) { return []; };
      return spuVoList.reduce((value, item) => {
        value.push({
          ...item,
          [CLASSIFICATION_OPTIONS_NAME]: [{
            classificationName: item.classificationNameUpdate,
            uuid: item.classificationUuidUpdate
          }]
        })
        return value;
      }, []);
    },
    // 根据关联品类更新所勾选的表格数据的品类树
    refreshCategoryPathFn (categoryData) {
      const { categoryUuid, categoryNo, categoryPath } = categoryData;
      this.tableInfo.selection.forEach(row => {
        const index = this.tableInfo.list.findIndex(item => {
          return row[this.uniqueKey] === item[this.uniqueKey];
        });
        if (index !== -1) {
          this.tableInfo.list[index].categoryUuidUpdate = categoryUuid;
          this.tableInfo.list[index].categoryNoUpdate = categoryNo;
          this.tableInfo.list[index].categoryPathUpdate = categoryPath;
        }
      });
    },
    // 获取请求归属部门接口入参
    getQueryParamListFn () {
      return this.tableInfo.selection.reduce((value, item) => {
        value.push({
          categoryUuid: item.categoryUuidUpdate,
          manageAreaUuid: item.manageAreaUuid
        });
        return value;
      }, []);
    },
    // 根据品类Uuid和管理区域更新表格数据的归属部门
    async refreshBelongingDeptNameFn () {
      const queryParamList = this.getQueryParamListFn();
      const data = { queryParamList };
      const { url, type } = this.apiObj.getBelongingDeptList;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data);
        this.tableInfo.loading = false;
        if (!isResponseSuccess(res)) { return false; }
        this.tableInfo.list.forEach(row => {
          const {
            hrDepartmentName, hrDepartmentNumber
          } = this.findMappingBelongingDeptNameFn(row, res.retData);
          row.belongingDeptName = hrDepartmentName;
          row.belongingDeptCode = hrDepartmentNumber;
        });
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 查找对应的归属部门
    findMappingBelongingDeptNameFn (row, retData) {
      const key = row.manageAreaUuid + '_' + row.categoryUuidUpdate;
      if (!retData[key]) {
        return {
          hrDepartmentName: '',
          hrDepartmentNumber: ''
        };
      }
      const data = retData[key][0];
      return data;
    },
    // 根据categoryUuid更新对应的归类信息
    async handleRefreshClassificationInfo (row) {
      if (!row.categoryUuidUpdate) { return false; }
      const data = {}
      const { url, type } = this.apiObj.getByCategoryUuid;
      const apiUrl = `${url}?categoryUuid=${row.categoryUuidUpdate}`;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(apiUrl, type, data);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          row[CLASSIFICATION_OPTIONS_NAME] = res.retData;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 根据关联品类查询品类及归类信息
    async getCateInfoByUuidFn (categoryUuid) {
      const { url, type } = this.apiObj.getCateInfo;
      const apiUrl = `${url}?categoryUuid=${categoryUuid}`;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(apiUrl, type, {});
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          const { classificationUuid, classificationName, taxCode, taxRate } = res.retData;
          this.tableInfo.selection.forEach(row => {
            row[CLASSIFICATION_OPTIONS_NAME] = [{
              classificationName: classificationName,
              uuid: classificationUuid
            }]
            row.classificationUuidUpdate = classificationUuid;
            row.classificationNameUpdate = classificationName;
            row.taxCodeUpdate = taxCode;
            row.taxRateUpdate = taxRate;
          })
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 下拉选择归类
    handleSelectClassification ({ row, target }) {
      if (!target) { return false; }
      const { classificationName, taxCateNo, taxRate, uuid } = target;
      row.classificationNameUpdate = classificationName;
      row.classificationUuidUpdate = uuid;
      row.taxCodeUpdate = taxCateNo;
      row.taxRateUpdate = taxRate;
    },
    // 删除
    handleRemoveRow ({ index }) {
      this.tableInfo.list.splice(index, 1);
    },
  }
}
</script>
